<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import NavBar from './NavBar.vue';
import { ElMessage } from 'element-plus'; // 导入 Element Plus 的消息提示组件
import { addUserInfo, editUserInfo, getUserByPhone, analyzeTongueImage } from '../api/user'; // 添加analyzeTongueImage导入
// 导入医生API
import { getDoctorList } from '../api/doctor';
// 删除axios导入，因为我们使用自定义API方法

const router = useRouter();
const showLoginDropdown = ref(false);
const showLoginAlert = ref(false);
// 添加功能提示框状态
const showFeaturePrompt = ref(false);
// 当前功能名称
const currentFeature = ref('');
// 提示框位置
const promptPosition = ref({ top: 0, left: 0 });

// 用户信息表单数据
const userInfo = ref({
  name: '',
  sex: '男',
  age: '',
  phone: '',
  username: '',
  password: '',
  constitution: ''
});

// 是否为注册
const needRegister = ref(false);

// 原始用户数据，用于重置
const originalUserInfo = ref({});

// 页面加载时获取用户信息
onMounted(() => {
  // 尝试从localStorage获取用户信息
  const storedUserInfo = localStorage.getItem('userInfo');
  
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo);
    originalUserInfo.value = { ...userInfo.value };
  } else {
    // 如果没有用户信息，检查是否需要注册
    const tempPhone = localStorage.getItem('tempPhone');
    const register = localStorage.getItem('needRegister');
    
    if (tempPhone) {
      userInfo.value.phone = tempPhone;
    }
    
    if (register === 'true') {
      needRegister.value = true;
    }
  }
});

// 关闭功能提示框
const closeFeaturePrompt = () => {
  showFeaturePrompt.value = false;
};

// 从提示框跳转到登录页面
const goToLoginFromPrompt = () => {
  showFeaturePrompt.value = false;
  router.push('/login');
};

// 返回首页
const goBack = () => {
  router.push('/');
};

// 重置表单
const resetForm = () => {
  userInfo.value = { ...originalUserInfo.value };
};

// 更新用户信息
const updateUserInfo = async () => {
  try {
    // 构建用户数据
    const userData = {
      name: userInfo.value.name,
      sex: userInfo.value.sex,
      age: userInfo.value.age,
      phone: userInfo.value.phone,
      username: userInfo.value.username,
      password: userInfo.value.password,
      constitution: userInfo.value.constitution || ''
    };
    
    if (needRegister.value) {
      // 检查是否有必填字段为空
      if (!userData.name || !userData.phone || !userData.username || !userData.password) {
        ElMessage({
          message: '请填写必要的信息（姓名、电话、账号和密码）',
          type: 'warning',
          duration: 2000
        });
        return;
      }
      
      try {
        // 直接调用注册接口，不需要再登录管理员
        const result = await addUserInfo(userData);
        
        if (result && result.code === 0) {
          ElMessage({
            message: '注册成功，即将跳转到登录页面',
            type: 'success',
            duration: 2000
          });
          
          // 保存用户信息到本地
          localStorage.setItem('user', JSON.stringify({
            code: 0,
            data: userData
          }));
          localStorage.setItem('userInfo', JSON.stringify(userData));
          
          // 清除注册标记
          localStorage.removeItem('needRegister');
          localStorage.removeItem('tempPhone');
          needRegister.value = false;
          
          // 注册成功后跳转到登录页面
          setTimeout(() => {
            router.push('/login');
          }, 2000);
        } else {
          ElMessage({
            message: result?.msg || '注册失败，请稍后再试',
            type: 'error',
            duration: 2000
          });
        }
      } catch (err) {
        console.error('注册接口调用失败:', err);
        ElMessage({
          message: '注册失败: ' + (err.message || '服务器错误'),
          type: 'error',
          duration: 2000
        });
      }
    } else {
      // 更新用户信息逻辑
      try {
        // 先通过手机号查询用户信息获取ID
        const queryResult = await getUserByPhone(userData.phone);
        
        if (queryResult && queryResult.code === 0 && queryResult.data) {
          // 将查询到的ID添加到userData中
          userData.id = queryResult.data.id;
          
          // 调用后端更新接口
          const result = await editUserInfo(userData);
          
          if (result && result.code === 0) {
            // 更新本地存储的用户信息
            const updatedUser = {
              code: 0,
              data: {
                ...queryResult.data,
                name: userInfo.value.name,
                sex: userInfo.value.sex,
                age: userInfo.value.age,
                phone: userInfo.value.phone,
                username: userInfo.value.username,
                constitution: userInfo.value.constitution
              }
            };
            
            localStorage.setItem('user', JSON.stringify(updatedUser));
            localStorage.setItem('userInfo', JSON.stringify(userData));
            
            ElMessage({
              message: '用户信息更新成功',
              type: 'success',
              duration: 2000
            });
          } else {
            ElMessage({
              message: result?.msg || '更新失败，请稍后再试',
              type: 'error',
              duration: 2000
            });
          }
        } else {
          ElMessage({
            message: '无法获取用户信息，更新失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (err) {
        console.error('更新接口调用失败:', err);
        ElMessage({
          message: '更新失败: ' + (err.message || '服务器错误'),
          type: 'error',
          duration: 2000
        });
      }
    }
    
    // 更新原始数据
    originalUserInfo.value = { ...userInfo.value };
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage({
      message: '操作失败: ' + (error.message || '请稍后再试'),
      type: 'error',
      duration: 2000
    });
  }
};

// 医生选择相关
const doctorDialogVisible = ref(false);
const doctorList = ref([]);
const selectedDoctorId = ref('');
const doctorLoading = ref(false);

// 显示医生选择对话框
const showDoctorSelection = () => {
  // 检查用户是否登录
  const storedUserInfo = localStorage.getItem('userInfo');
  if (!storedUserInfo) {
    ElMessage({
      message: '请先登录后再使用在线咨询功能',
      type: 'warning',
      duration: 2000
    });
    router.push('/login');
    return;
  }
  
  doctorDialogVisible.value = true;
  loadDoctorList();
};

// 加载医生列表
const loadDoctorList = async () => {
  try {
    doctorLoading.value = true;
    const res = await getDoctorList({ status: '值班', del: 0 });
    if (res?.code === 0 && Array.isArray(res.data)) {
      doctorList.value = res.data;
      if (doctorList.value.length === 0) {
        ElMessage({
          message: '当前没有值班医生，请稍后再试',
          type: 'warning',
          duration: 2000
        });
      }
    } else {
      ElMessage({
        message: '没有找到值班医生',
        type: 'warning',
        duration: 2000
      });
    }
  } catch (error) {
    console.error('加载医生列表失败:', error);
    ElMessage({
      message: '加载医生列表失败',
      type: 'error',
      duration: 2000
    });
  } finally {
    doctorLoading.value = false;
  }
};

// 开始咨询
const startConsultation = () => {
  if (!selectedDoctorId.value) {
    ElMessage({
      message: '请选择一位医生',
      type: 'warning',
      duration: 2000
    });
    return;
  }
  
  // 获取当前用户信息
  const storedUserInfo = localStorage.getItem('userInfo');
  console.log('存储的用户信息字符串:', storedUserInfo);
  
  const userInfoObj = JSON.parse(storedUserInfo || '{}');
  console.log('解析后的用户信息对象:', userInfoObj);
  
  // 尝试从localStorage中的user对象获取ID
  const storedUser = localStorage.getItem('user');
  let userId = userInfoObj.id;
  
  // 如果userInfo中没有id，尝试从user对象中获取
  if (!userId && storedUser) {
    try {
      const userObj = JSON.parse(storedUser);
      console.log('解析后的user对象:', userObj);
      
      if (userObj.data && userObj.data.id) {
        userId = userObj.data.id;
        console.log('从user对象中获取的id:', userId);
      }
    } catch (e) {
      console.error('解析user对象失败:', e);
    }
  }
  
  if (!userId) {
    ElMessage({
      message: '无法获取用户ID，请重新登录',
      type: 'error',
      duration: 2000
    });
    router.push('/login');
    return;
  }
  
  // 关闭对话框
  doctorDialogVisible.value = false;
  
  // 跳转到聊天页面，传递医生ID和用户ID
  router.push({
    path: '/chat',
    query: {
      doctorId: selectedDoctorId.value,
      userId: userId,
      mode: 'patient' // 标识当前是患者模式
    }
  });
};

// 直接跳转到聊天页面
const goToChat = () => {
  // 检查用户是否登录
  const storedUserInfo = localStorage.getItem('userInfo');
  if (!storedUserInfo) {
    ElMessage({
      message: '请先登录后再使用在线咨询功能',
      type: 'warning',
      duration: 2000
    });
    router.push('/login');
    return;
  }
  
  // 获取当前用户信息
  const userInfo = JSON.parse(storedUserInfo || '{}');
  const userId = userInfo.id;
  
  if (!userId) {
    ElMessage({
      message: '请先登录',
      type: 'error',
      duration: 2000
    });
    router.push('/login');
    return;
  }
  
  // 直接跳转到聊天页面，只携带用户ID和模式
  router.push({
    path: '/chat',
    query: {
      userId: userId,
      mode: 'patient' // 标识当前是患者模式
    }
  });
};

// 舌象辨识相关
const tongueDialogVisible = ref(false);
const tongueImage = ref(null);
const tongueImageUrl = ref('');
const tongueResult = ref('');
const analyzing = ref(false);

// 显示舌象辨识对话框
const showTongueAnalysis = () => {
  // 检查用户是否登录
  const storedUserInfo = localStorage.getItem('userInfo');
  if (!storedUserInfo) {
    ElMessage({
      message: '请先登录后再使用舌象辨识功能',
      type: 'warning',
      duration: 2000
    });
    router.push('/login');
    return;
  }
  
  tongueDialogVisible.value = true;
  // 重置状态
  tongueImage.value = null;
  tongueImageUrl.value = '';
  tongueResult.value = '';
};

// 处理图片上传
const handleTongueImageChange = (e) => {
  const file = e.target.files[0];
  if (!file) return;
  
  // 检查文件类型
  if (!file.type.includes('image')) {
    ElMessage({
      message: '请上传图片文件',
      type: 'error',
      duration: 2000
    });
    return;
  }
  
  // 检查文件大小（限制为5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage({
      message: '图片大小不能超过5MB',
      type: 'error',
      duration: 2000
    });
    return;
  }
  
  tongueImage.value = file;
  
  // 创建预览URL
  tongueImageUrl.value = URL.createObjectURL(file);
};

// 进行舌象辨识
const analyzeTongue = async () => {
  if (!tongueImage.value) {
    ElMessage({
      message: '请先上传舌象图片',
      type: 'warning',
      duration: 2000
    });
    return;
  }
  
  analyzing.value = true;
  tongueResult.value = '';
  
  try {
    // 将图片转为Base64
    const reader = new FileReader();
    reader.readAsDataURL(tongueImage.value);
    
    reader.onload = async () => {
      const base64Image = reader.result.split(',')[1]; // 移除data:image/jpeg;base64,前缀
      
      // 调用API方法而不是直接使用axios
      const response = await analyzeTongueImage(base64Image);
      
      if (response.code === 0) {
        tongueResult.value = response.data;
        
        // 更新用户体质信息
        if (userInfo.value && tongueResult.value) {
          userInfo.value.constitution = tongueResult.value;
          
          // 从userInfo中获取id
          const storedUserInfo = localStorage.getItem('userInfo');
          if (storedUserInfo) {
            try {
              const userInfoObj = JSON.parse(storedUserInfo);
              if (userInfoObj.id) {
                // 构建更新数据
                const updateData = {
                  id: userInfoObj.id,
                  physique: tongueResult.value
                };
                
                // 调用更新接口
                await editUserInfo(updateData);
                
                // 更新本地存储
                userInfoObj.constitution = tongueResult.value;
                localStorage.setItem('userInfo', JSON.stringify(userInfoObj));
                
                // 同时更新user对象
                const storedUser = localStorage.getItem('user');
                if (storedUser) {
                  const userObj = JSON.parse(storedUser);
                  if (userObj.data) {
                    userObj.data.constitution = tongueResult.value;
                    localStorage.setItem('user', JSON.stringify(userObj));
                  }
                }
                
                ElMessage({
                  message: '体质信息已更新',
                  type: 'success',
                  duration: 2000
                });
              }
            } catch (e) {
              console.error('更新用户体质信息失败:', e);
            }
          }
        }
      } else {
        ElMessage({
          message: response.msg || '辨识失败，请重试',
          type: 'error',
          duration: 2000
        });
      }
    };
  } catch (error) {
    console.error('舌象辨识失败:', error);
    ElMessage({
      message: '辨识失败: ' + (error.message || '服务器错误'),
      type: 'error',
      duration: 2000
    });
  } finally {
    analyzing.value = false;
  }
};
</script>

<template>
  <div class="personal-container">
    <NavBar />
    
    <div class="content">
      <h1 class="title">
        个人中心
        <span v-if="needRegister" class="register-badge">注册</span>
      </h1>
      
      <div class="user-form">
        <div class="form-row">
          <div class="form-group">
            <label for="name">姓名</label>
            <input type="text" id="name" v-model="userInfo.name" placeholder="请输入姓名">
          </div>
          <div class="form-group">
            <label for="sex">性别</label>
            <select id="sex" v-model="userInfo.sex">
              <option value="男">男</option>
              <option value="女">女</option>
              <option value="其他">其他</option>
            </select>
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label for="age">年龄</label>
            <input type="number" id="age" v-model="userInfo.age" placeholder="请输入年龄">
          </div>
          <div class="form-group">
            <label for="phone">电话</label>
            <input type="tel" id="phone" v-model="userInfo.phone" placeholder="请输入电话号码" readonly>
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-group">
            <label for="username">账号名</label>
            <input type="text" id="username" v-model="userInfo.username" placeholder="请输入账号名">
          </div>
          <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" v-model="userInfo.password" placeholder="请输入密码">
          </div>
        </div>
        
        <div class="form-row">
          <div class="form-group full-width">
            <label for="constitution">体质</label>
            <input type="text" id="constitution" v-model="userInfo.constitution" placeholder="体质类型" readonly>
          </div>
        </div>
        
        <div class="form-actions">
          <button class="btn btn-back" @click="goBack">返回</button>
          <button class="btn btn-reset" @click="resetForm">重置</button>
          <button class="btn btn-update" @click="updateUserInfo">{{ needRegister ? '注册' : '更新' }}</button>
        </div>
      </div>
    </div>

    <!-- 添加询问按钮 -->
    <button class="consult-button" @click="showDoctorSelection">
      <i class="el-icon-chat-dot-round"></i>
      在线咨询
    </button>
    
    <!-- 医生选择对话框 -->
    <el-dialog
      v-model="doctorDialogVisible"
      title="选择医生进行咨询"
      width="500px"
      :close-on-click-modal="false">
      <div class="doctor-selection">
        <el-skeleton :rows="3" animated v-if="doctorLoading" />
        <template v-else>
          <div v-if="doctorList.length === 0" class="no-doctor">
            当前没有值班医生，请稍后再试
          </div>
          <el-radio-group v-model="selectedDoctorId" v-else>
            <div v-for="doctor in doctorList" :key="doctor.id" class="doctor-item">
              <el-radio :label="doctor.id">
                <div class="doctor-info">
                  <div class="doctor-name">{{ doctor.name }}</div>
                  <div class="doctor-title">{{ doctor.title }}</div>
                  <div class="doctor-department">{{ doctor.department }}</div>
                </div>
              </el-radio>
            </div>
          </el-radio-group>
        </template>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="doctorDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="startConsultation" :disabled="!selectedDoctorId">
            开始咨询
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除医生选择对话框 -->
    
    <!-- 登录提示弹窗 -->
    <div class="login-alert" v-if="showLoginAlert">
      <div class="alert-content">
        <p>该功能需要登录后解锁</p>
      </div>
    </div>

    <!-- 功能提示小弹窗 -->
    <div class="feature-prompt-mini" v-if="showFeaturePrompt" 
         :style="{ top: promptPosition.top + 'px', left: promptPosition.left + 'px' }">
      <div class="prompt-arrow"></div>
      <div class="prompt-content">
        <p>{{ currentFeature === 'personal' ? '个人中心' : '数据分析' }}需要登录</p>
        <div class="prompt-buttons">
          <button class="cancel-btn" @click="closeFeaturePrompt">取消</button>
          <button class="login-btn" @click="goToLoginFromPrompt">去登录</button>
        </div>
      </div>
    </div>
    
    <!-- 添加舌象辨识按钮 -->
    <button class="tongue-button" @click="showTongueAnalysis">
      <i class="el-icon-view"></i>
      舌象辨识
    </button>
    
    <!-- 舌象辨识对话框 -->
    <el-dialog
      v-model="tongueDialogVisible"
      title="舌象辨识"
      width="500px"
      :close-on-click-modal="false">
      <div class="tongue-analysis">
        <div class="upload-area">
          <div class="upload-preview" v-if="tongueImageUrl">
            <img :src="tongueImageUrl" alt="舌象图片预览" />
          </div>
          <div class="upload-placeholder" v-else>
            <i class="el-icon-upload"></i>
            <p>点击上传舌象图片</p>
          </div>
          <input 
            type="file" 
            accept="image/*" 
            @change="handleTongueImageChange" 
            class="file-input"
            id="tongue-image-input"
          />
          <label for="tongue-image-input" class="upload-button">选择图片</label>
        </div>
        
        <div class="analysis-result" v-if="tongueResult">
          <h3>辨识结果</h3>
          <p>您的体质类型为: <span class="result-type">{{ tongueResult }}</span></p>
        </div>
        
        <div class="analysis-actions">
          <el-button @click="tongueDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="analyzeTongue" 
            :loading="analyzing"
            :disabled="!tongueImage">
            {{ analyzing ? '辨识中...' : '开始辨识' }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped src="../css/personal.css"></style>

<style scoped>
/* 添加新样式 */
.consult-button {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 100;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #8B4513;
  color: white;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
  cursor: pointer;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 12px;
}

.consult-button i {
  font-size: 24px;
  margin-bottom: 4px;
}

.consult-button:hover {
  background-color: #A0522D;
}

.doctor-selection {
  max-height: 400px;
  overflow-y: auto;
}

.doctor-item {
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.doctor-item:hover {
  background-color: #f9f6f2;
}

.doctor-info {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
}

.doctor-name {
  font-weight: bold;
  font-size: 16px;
  color: #8B4513;
}

.doctor-title {
  font-size: 14px;
  color: #CD853F;
  margin-top: 5px;
}

.doctor-department {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.no-doctor {
  text-align: center;
  padding: 20px;
  color: #999;
}

/* 舌象辨识按钮样式 */
.tongue-button {
  position: fixed;
  bottom: 30px;
  right: 100px; /* 位于咨询按钮旁边 */
  z-index: 100;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #CD853F; /* 与咨询按钮区分 */
  color: white;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
  cursor: pointer;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 12px;
}

.tongue-button i {
  font-size: 24px;
  margin-bottom: 4px;
}

.tongue-button:hover {
  background-color: #DEB887;
}

/* 舌象辨识对话框样式 */
.tongue-analysis {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-area {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.upload-preview {
  width: 300px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  margin-bottom: 10px;
}

.upload-preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.upload-placeholder {
  width: 300px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #8c939d;
  margin-bottom: 10px;
}

.upload-placeholder i {
  font-size: 28px;
  margin-bottom: 10px;
}

.file-input {
  display: none;
}

.upload-button {
  display: inline-block;
  padding: 8px 16px;
  background-color: #8B4513;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.upload-button:hover {
  background-color: #A0522D;
}

.analysis-result {
  width: 100%;
  padding: 15px;
  background-color: #f9f6f2;
  border-radius: 4px;
  margin-bottom: 20px;
}

.analysis-result h3 {
  margin-top: 0;
  color: #8B4513;
}

.result-type {
  font-weight: bold;
  color: #8B4513;
  font-size: 18px;
}

.analysis-actions {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
</style>
